import docx
from docx.oxml.shared import OxmlElement, qn
from docx.enum.dml import MSO_THEME_COLOR_INDEX
from docx.opc.constants import RELATIONSHIP_TYPE
from loguru import logger
def add_hyperlink(paragraph, text, url):
    """添加超链接

    :param paragraph: 追加的段落
    :param text: 文本
    :param url: 链接
    """
    r_id = paragraph.part.relate_to(url, RELATIONSHIP_TYPE.HYPERLINK, is_external=True)  # 关联超链接
    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('r:id'), r_id)
    run = paragraph.add_run(text)
    run.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    run.font.underline = True
    hyperlink.append(run._r)
    paragraph._element.append(hyperlink)
    return hyperlink

def save_footnotes(footnotes:list,document:docx.Document,conf:dict):
    if conf.get('footnote_inline',False):
        #脚注写在一行里
        paragraph=document.add_paragraph()
        for footnote in footnotes:
            paragraph.add_run(f"[{footnotes.index(footnote)+1}]{footnote}  ")
    else:
        for footnote in footnotes:
            paragraph=document.add_paragraph()
            paragraph.add_run(f"[{footnotes.index(footnote)+1}]{footnote}")
    logger.debug(f'已保存脚注，共计{len(footnotes)}条')

def force_to_text(nodes:list)->str:
    text=''.join(map(lambda c:c.get('Data') if c.get('Data') else c.get('TextMarkTextContent',''),nodes))#把标记和文本组合起来
    return text

def add_table(node:dict,document:docx.Document,conf:dict):
    node['Children'][0]=node['Children'][0]['Children'][0]
    table=document.add_table(rows=len(node['Children']),cols=len(node['Children'][0]['Children']))
    for row in node['Children']:
        for col in row['Children']:
            table.cell(node['Children'].index(row),row['Children'].index(col)).text=force_to_text(col['Children'])#第一行不行